package com.bigevent.service.impl;

import com.bigevent.mapper.ArticleMapper;
import com.bigevent.pojo.Article;
import com.bigevent.pojo.PageBean;
import com.bigevent.service.ArticleServiece;
import com.bigevent.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleServiece {

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public void add(Article article) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        article.setCreateUser((Integer) claims.get("id"));
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, String state, Integer categoryId) {
        // 1.创建pageBean对象
        PageBean<Article> pb = new PageBean<>();

        // 2.开启分页查询
        PageHelper.startPage(pageNum,pageSize);

        // 3.调用mapper
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        List<Article> as = articleMapper.list(userId,state,categoryId);
        // page中提供了方法，可以获取pagehelper分页查询后 得到的总记录数和当前页数据
        Page<Article> p = (Page<Article>) as;

        // 把数据填充到pageBean中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
